<template>
  <div class="goods-image" >
    <!-- 放大镜弹层 -->
    <div class="large" :style="[{
      backgroundPosition:`${bg.x}px ${bg.y}px`,
      backgroundImage:`url(${imageList[getimg]})`}]" v-show="!isOutside"></div>

    <div class="middle"  ref="target"  >
      <img :src="imageList[getimg]" alt="" >
       <!-- 正方体蒙层滑块 -->
       <div class="layer" :style="{left:`${pos.left}px`,top:`${pos.top}px`}" v-show="!isOutside"></div>
    </div>
    <ul class="small">
      <!-- 右边小图 -->
      <li v-for="(img,i) in imageList" :key="i" @mouseenter="getimg = i">
        <img :src="img" alt="">
      </li>
    </ul>
  </div>
</template>
<script>
import { ref, watch } from 'vue'
import { useMouseInElement } from '@vueuse/core'
export default {
  name: 'GoodsImage',
  props: {
    imageList: {
      type: Array,
      default: () => ([])
    }
  },
  setup () {
    const getimg = ref(0)
    // 放大镜实现
    // 前置知识：浏览器坐标都是从左上角开始的
    // 1.获取元素内鼠标移动的坐标
    // 2.监听元素内鼠标移动的坐标变化=》控制蒙层移动=》计算lef和top
    // 蒙层移动的范围 ： 100<pos<300
    // 蒙层的计算公式： lef = elementX - 100 | top = elementY - 100
    const target = ref(null)
    const { elementX, elementY, isOutside } = useMouseInElement(target)
    // console.log()
    // 蒙层区放大2倍
    const bg = ref({ x: 0, y: 0 })
    // 定义蒙层位置变量
    const pos = ref({ left: 0, top: 0 })
    watch([elementX, elementY], () => {
      // console.log(elementX.value)
      // 横轴
      if (elementX.value < 100) {
        pos.value.left = 0
      } else if (elementX.value > 300) {
        pos.value.left = 200
      } else {
        pos.value.left = elementX.value - 100
      }
      // 纵轴
      if (elementY.value < 100) {
        pos.value.top = 0
      } else if (elementY.value > 300) {
        pos.value.top = 200
      } else {
        pos.value.top = elementY.value - 100
      }
      bg.value.x = -pos.value.left * 2
      bg.value.y = -pos.value.top * 2
    })

    return { getimg, target, elementX, elementY, isOutside, pos, bg }
  }
}
</script>
<style scoped lang="less">
.goods-image {
  width: 480px;
  height: 400px;
  position: relative;
  display: flex;
  // 放大镜弹层
  .large {
    position: absolute;
    top: 0;
    left: 412px;
    width: 400px;
    height: 400px;
    z-index:500;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    background-repeat: no-repeat;
    background-size: 800px 800px;
    background-color: #f8f8f8;
  }
  .middle {
    width: 400px;
    height: 400px;
    background: #f5f5f5;
    // <!--配套样式 -->
.layer {
  width: 200px;
  height: 200px;
  background: rgba(0, 0, 0, 0.2);
  left: 0;
  top: 0;
  position: absolute;
}
  }
  .small {
    width: 80px;
    li {
      width: 68px;
      height: 68px;
      margin-left: 12px;
      margin-bottom: 15px;
      cursor: pointer;
      &:hover,&.active {
        border: 2px solid @xtxColor;
      }
    }
  }
}
</style>
